package com.cebbank.yyi.springbootapp.filter;

import lombok.RequiredArgsConstructor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: yyi
 * @version: 1.0
 **/
//@Component
//@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
//        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
//        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
//@RequiredArgsConstructor
public class SqlInterceptor implements Interceptor {


    private  ApplicationContext applicationContext;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        List<SqlMappersFilter> collect = applicationContext.getBeansOfType(SqlMappersFilter.class)
                .values()
                .stream().sorted(Comparator.comparing(SqlMappersFilter::getOrder)
                        .thenComparing(sqlMapperFilter -> sqlMapperFilter.getAppName().charAt(0)))
                .collect(Collectors.toList());
        SqlMapperFilterChain chain = new SqlMapperFilterChain(collect);
        return chain.doFilter(invocation);
    }


}